﻿using JewererBasic.Classes;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JewererBasic.Controllers
{
    public class ReportController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ExportReportProduct(string productId = "")
        {
            if (string.IsNullOrEmpty(productId) == false)
            {
                MSQDBEntities dc = new MSQDBEntities();

                /*Get all needed data*/
                // DSProductStone
                var DSStone = (from d in dc.GetProductStone(productId)
                               select d).ToList();
                ReportDataSource sourceStone = new ReportDataSource("DSProductStone", DSStone);
                // DSProductCom
                var DSCom = (from d in dc.GetProductCom(productId)
                             select d).ToList();
                ReportDataSource sourceCom = new ReportDataSource("DSProductCom", DSCom);
                // DSProductMould
                var DSMould = (from d in dc.GetProductMould(productId)
                               select d).ToList();
                ReportDataSource sourceMould = new ReportDataSource("DSProductMould", DSMould);
                // DSProductionCard
                var DSProductionCard = (from d in dc.GetProductionCard(productId)
                                        select d).ToList();
                ReportDataSource sourceProductionCard = new ReportDataSource("DSProductionCard", DSProductionCard);
                // DSProductProcess
                var DSProcess = (from d in dc.GetProductProcess(productId)
                                 select d).ToList();
                ReportDataSource sourceProcess = new ReportDataSource("DSProductProcess", DSProcess);
                // Image Path             
                string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

                /*Set up Report*/

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;

                // Set up viewer
                ReportViewer viewer = new ReportViewer();
                viewer.ProcessingMode = ProcessingMode.Local;
                viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPProductionCard.rdlc");
                viewer.LocalReport.EnableExternalImages = true; // enable image in report
                // Set DataSources
                viewer.LocalReport.DataSources.Add(sourceProductionCard);
                viewer.LocalReport.DataSources.Add(sourceStone);
                viewer.LocalReport.DataSources.Add(sourceProcess);
                viewer.LocalReport.DataSources.Add(sourceCom);
                viewer.LocalReport.DataSources.Add(sourceMould);

                // Set Parameters
                viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

                byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

                // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=" + productId + "." + extension);
                Response.BinaryWrite(bytes); // create the file
                Response.Flush(); // send it to the client to download
                return File(bytes, "application/pdf");
            }
            return View();
        }

        public ActionResult ExportReportBagHistory(string bagId = "000017")
        {
            if (string.IsNullOrEmpty(bagId) == false)
            {
                MSQDBEntities dc = new MSQDBEntities();

                /*Get all needed data*/
                // DSProductStone
                var DSBagHistory = (from d in dc.GetBagHistory(bagId)
                                    select d).ToList();
                ReportDataSource sourceBagHistory = new ReportDataSource("DSBagHistory", DSBagHistory);
                // Image Path             
                //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

                /*Set up Report*/

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;

                // Set up viewer
                ReportViewer viewer = new ReportViewer();
                viewer.ProcessingMode = ProcessingMode.Local;
                viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPBagHistory.rdlc");
                viewer.LocalReport.EnableExternalImages = true; // enable image in report
                // Set DataSources                
                viewer.LocalReport.DataSources.Add(sourceBagHistory);

                // Set Parameters
                //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

                byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

                // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=" + bagId + "_History" + "." + extension);
                Response.BinaryWrite(bytes); // create the file
                Response.Flush(); // send it to the client to download
                return File(bytes, "application/pdf");
            }
            return View();
        }

        public ActionResult ExportReportBag(/*List<string> bagIds*/ params string[] bagIds)
        {
            //test datas
            //bagIds = new List<string>();
            //bagIds.Add("000017");
            //bagIds.Add("000018");
            //bagIds.Add("000019");
            //bagIds.Add("000020");

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty, encoding = string.Empty, extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPBag.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            viewer.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
            // Get all Bag data
            List<BagDataSource_Result> DSBag = new List<BagDataSource_Result>();
            foreach (string bagId in bagIds)
            {
                if (string.IsNullOrEmpty(bagId) == false)
                {
                    BagDataSource_Result bagDataSource = ReportController.GetData(bagId);
                    bagDataSource.ProductImage = new Uri(Server.MapPath("~/Uploads/" + bagDataSource.ProductImage)).AbsoluteUri;
                    bagDataSource.BagImage = new Uri(Server.MapPath("~/Content/Barcode/" + bagDataSource.BagImage)).AbsoluteUri;
                    DSBag.Add(bagDataSource);
                }
            }

            // Set DataSources                
            viewer.LocalReport.DataSources.Add(new ReportDataSource("DSBag", DSBag));
            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + "BagList." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
            MSQDBEntities dc = new MSQDBEntities();
            string bagId = e.Parameters["BagId"].Values.First();
            e.DataSources.Add(new ReportDataSource("DSBagProcess", dc.GetBagProcess(bagId).ToList()));
        }

        /*Helper function*/
        public static BagDataSource_Result GetData(string bagId)
        {
            if (string.IsNullOrWhiteSpace(bagId) == false)
            {
                using (MSQDBEntities dc = new MSQDBEntities())
                {
                    var bag = dc.BAGs.Find(bagId);
                    if (bag != null)
                    {
                        ORDER order = bag.ORDER_PRODUCT.ORDER;
                        ORDER_PRODUCT orderProduct = bag.ORDER_PRODUCT;
                        PRODUCT product = orderProduct.PRODUCT;
                        List<BAG_STONE> stones = bag.BAG_STONE.ToList();
                        List<BAG_MOULD> moulds = bag.BAG_MOULD.ToList();

                        BagDataSource_Result result = new BagDataSource_Result();
                        result.BagId = bag.Id;
                        result.BagQty = bag.Number;
                        result.Customer = order.IdCustomer;
                        result.FinishWeek = (int)order.FinishWeek;
                        result.OrderId = order.IdOrder;
                        result.ProductId = product.Id;
                        result.ProductImage = product.Drawing;
                        result.ProductionKind = orderProduct.Gold;
                        result.ProductRemark = product.Remark;
                        result.ProductSize = orderProduct.Size;
                        result.ProductType = product.TYPE.Name;
                        result.BagImage = order.IdOrder + "_" + bag.Id + ".png";
                        result.ProductGamma = product.GAMMA.Name;

                        // Get List
                        result.ListMould = "";
                        result.ListStone = "";
                        string strStone = "";
                        string strMould = "";
                        string separatorStone = "\r\n";
                        string separatorMould = " \r\n";
                        
                        // Get list stones
                        foreach (var item in stones)
                        {
                            strStone += item.TotalQty + "_" + item.STONE.Name + ":" + item.STONE.Id + separatorStone;
                        }
                        if (strStone.Length != 0)
                            result.ListStone = strStone.Trim().Substring(0, strStone.Length - separatorStone.Length);
                        
                        // Get list components
                        foreach (var item in moulds)
                        {
                            strMould += item.TotalQty + "_" + item.MOULD.IdMould + separatorMould;
                        }
                        if(strMould.Length!=0)
                            result.ListMould = strMould.Trim().Substring(0, strMould.Length - separatorMould.Length);

                        return result;
                    }
                }
            }
            return null;
        }

        public ActionResult ImportedStone(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSImportedStone = (from d in dc.GetImportedStone(id)
                                select d).ToList();
            ReportDataSource source = new ReportDataSource("DSImportedStone", DSImportedStone);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPImportedStone.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_StoneImport" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            
            return File(bytes, "application/pdf");
        }

        public ActionResult ExportedStoneToStaff(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSExportedStone = (from d in dc.GetExportedStoneToStaff(id)
                                   select d).ToList();
            ReportDataSource source = new ReportDataSource("DSExportedStoneToStaff", DSExportedStone);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPExportedStoneToStaff.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_StaffExportStone" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        public ActionResult ExportedStoneToBag(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSExportedStone = (from d in dc.GetExportedStoneToBag(id)
                                   select d).ToList();
            ReportDataSource source = new ReportDataSource("DSExportedStoneToBag", DSExportedStone);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPExportedStoneToBag.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_BagExportStone" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        public ActionResult ImportedComponent(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSImportedComponent = (from d in dc.GetImportedComponent(id)
                                   select d).ToList();
            ReportDataSource source = new ReportDataSource("DSImportedComponent", DSImportedComponent);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPImportedComponent.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_ComponentImport" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        public ActionResult ExportedComponentToStaff(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSExportedComponent = (from d in dc.GetExportedComponentToStaff(id)
                                   select d).ToList();
            ReportDataSource source = new ReportDataSource("DSExportedComponentToStaff", DSExportedComponent);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPExportedComponentToStaff.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_StaffExportComponent" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        public ActionResult ExportedComponentToBag(int id)
        {
            MSQDBEntities dc = new MSQDBEntities();

            var DSExportedComponent = (from d in dc.GetExportedComponentToBag(id)
                                   select d).ToList();
            ReportDataSource source = new ReportDataSource("DSExportedComponentToBag", DSExportedComponent);
            // Image Path             
            //string imagePath = new Uri(Server.MapPath("~/Uploads/" + dc.PRODUCTs.Find(productId).Drawing)).AbsoluteUri;

            /*Set up Report*/

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPExportedComponentToBag.rdlc");
            viewer.LocalReport.EnableExternalImages = true; // enable image in report
            // Set DataSources                
            viewer.LocalReport.DataSources.Add(source);

            // Set Parameters
            //viewer.LocalReport.SetParameters(new ReportParameter("ImagePath", imagePath));

            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + id + "_BagExportComponent" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }
       
        public ActionResult ExportReportWasteById(int id = -1)
        {
            if (id != -1)
            {
                MSQDBEntities db = new MSQDBEntities();
                ReportDataSource rds = new ReportDataSource("DSWasteReportById", db.GetWasteReportById(id));

                // Set up viewer
                ReportViewer viewer = new ReportViewer();
                viewer.ProcessingMode = ProcessingMode.Local;
                viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPWasteReportById.rdlc");
                viewer.LocalReport.DataSources.Add(rds);

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;
                byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=" + "Waste_Report" + "." + extension);
                Response.BinaryWrite(bytes); // create the file
                Response.Flush(); // send it to the client to download
                return File(bytes, "application/pdf");
            }
            else
            {
                // Infor no waste in this month
            }
            //ErrorLog.Instance.InternalErrors.Clear();
            ErrorLog.Instance.InternalErrors.Add("There is no Waste.");
            return RedirectToAction("Index", "Error");
        }

        public ActionResult ExportReportCurentWaste()
        {
            MSQDBEntities db = new MSQDBEntities();            
            ReportDataSource rds = new ReportDataSource("DSCurrentWaste", db.GetCurrentWasteState());

            // Set up viewer
            ReportViewer viewer = new ReportViewer();
            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.ReportPath = Server.MapPath("~/Reports" + "//RPCurrentWaste.rdlc");
            viewer.LocalReport.DataSources.Add(rds);

            // Variables
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;
            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + "Waste_Report" + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush(); // send it to the client to download
            return File(bytes, "application/pdf");
        }

        public ActionResult Process_Report_View()
        {
            string reporter = "Hoai Sang";
            return View(Process_Report_Repository.Generate_Report(reporter));
        }
    }
}
